package com.gillion.grape.fros.ui.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.xml.sax.SAXException;

import com.gillion.grape.core.Logger;

/**<pre></pre>
 * @Author   chich
 * @Version  1.0
 * @Date     2012-2-5
 * @example  使用示例：略。
 */
public class Dom4jUtil {
	public static Element getChildElementByTagName(Element parentElement, String tagName){
		for (Iterator j = parentElement.elementIterator(); j.hasNext();) {
			Element node = (Element) j.next();
			if(tagName.equals(node.getName())){
				return node;
			}
		}
		return null;
	}
	
	public static List<Element> getChildElementsByTagName(Element parentElement, String tagName){
		List<Element> lstElement = new ArrayList<Element>();
		for(Iterator j = parentElement.elementIterator(); j.hasNext();) {
			Element node = (Element) j.next();
			if(tagName.equals(node.getName())){
				lstElement.add(node);
			}
		}
		return lstElement;
	}
	
	public static Element getChildElementByAttribute(Element parentElement, String attribute, String value){
		for (Iterator j = parentElement.elementIterator(); j.hasNext();) {
			Element node = (Element) j.next();
			if(value.equals(node.attributeValue(attribute))){
				return node;
			}
		}
		return null;
	}
	
	public static void saveDocument2File(Document document, String filePath){
		try{
			Writer fileWriter = new FileWriter(filePath);
			OutputFormat format = OutputFormat.createPrettyPrint();
			XMLWriter xmlWriter = new XMLWriter(fileWriter, format);
			xmlWriter.write(document);
			xmlWriter.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static Document loadXml2Document(String filePath){
		Document document = null;
		try {
			File inputXml = new File(filePath);
			SAXReader saxReader = new SAXReader(false);
//			saxReader.setFeature("", false);
			document = saxReader.read(inputXml);
		} catch (Exception e) {
		}
		return document;
	}
	
}
